<template>
    <div class="trader-order">
        <!-- 将页面切换下拉框移到最上方 -->
        <div class="page-switch">
            <el-select v-model="currentPage" @change="handlePageChange">
                <el-option label="发起流程" value="traderOrder"></el-option>
                <el-option label="审批流程" value="orderApprove"></el-option>
            </el-select>
        </div>

        <!-- 客户信息区域 -->
        <div class="section-card">
            <div class="section-header">
                <i class="el-icon-user"></i>
                <span>分销商信息</span>
            </div>
            <el-form :model="formData" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="选择分销商">
                            <el-select v-model="formData.distributorCode" placeholder="请选择客户"
                                @change="handleCustomerChange">
                                <el-option v-for="item in customerList" :key="item.distributorCode"
                                    :label="item.distributorName" :value="item.distributorCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="分销商联系方式">
                            <el-input v-model="formData.companyPhone" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="分销商联系人">
                            <el-input v-model="formData.companyContact" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="订单签订日期">
                            <el-date-picker v-model="formData.validityEndDate" type="date"></el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="销售订单编号">
                            <el-input v-model="formData.orderNo" disabled></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="销售负责人">
                            <el-input v-model="formData.saleMan" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 销售产品明细 -->
        <div class="section-card">
            <div class="section-header">
                <i class="el-icon-goods"></i>
                <span>产品明细</span>
            </div>
            <el-table :data="productList" border>
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column label="选择产品" width="220">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.id" placeholder="请选择"
                            @change="(val) => handleProductChange(val, scope.$index)">
                            <el-option v-for="item in productOptions" :key="item.id" :label="item.productName"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <el-table-column prop="productCode" label="产品编码"></el-table-column>
                <el-table-column prop="stockQuantity" label="可用库存数量"></el-table-column>
                <el-table-column prop="salesQuantity" label="销售数量" width="180">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.salesQuantity" :min="0" :max="scope.row.stockQuantity"
                            @change="handleQuantityChange" controls-position="right">
                        </el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="salePrice" label="销售单价"></el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" class="delete-btn" @click="removeProduct(scope.$index)">
                            <i class="el-icon-delete"></i> 删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="table-operations">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addProduct">添加产品</el-button>
            </div>
            <!-- 添加产品总价值计算 -->
            <div class="price-summary">
                <span>产品总价值：{{ totalProductValue }} 元</span>
            </div>
        </div>

        <!-- 将发货计划改为产品条款 -->
        <div class="section-card">
            <div class="section-header">
                <i class="el-icon-document"></i>
                <span>产品条款</span>
            </div>
            <el-form :model="priceTerms" label-width="150px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="总原价">
                            <el-input v-model="priceTerms.totalOriginalPrice" disabled>
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="折扣率（%）">
                            <el-input-number v-model="priceTerms.discountRate" :min="0" :max="100" :precision="2"
                                @change="calculatePrices">
                                <template slot="append">%</template>
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="优惠金额">
                            <el-input v-model="priceTerms.discountAmount" disabled>
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="订单金额(含税)">
                            <el-input v-model="priceTerms.totalPriceWithTax" disabled>
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="订单金额(不含税)">
                            <el-input v-model="priceTerms.totalPriceWithoutTax" disabled>
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="订单毛利率">
                            <el-input v-model="priceTerms.grossMargin" disabled>
                                <template slot="append">%</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按钮，移除下拉框 -->
        <div class="form-actions">
            <el-button type="primary" icon="el-icon-check" @click="applyOrder">提交申请</el-button>
            <el-button icon="el-icon-close" @click="cancel">取消</el-button>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            currentPage: 'traderOrder',  // 修改初始值
            formData: {
                distributorCode: '',  // 分销商编码
                companyPhone: '',     // 联系方式
                companyContact: '',   // 联系人
                validityEndDate: '',  // 签订日期
                orderNo: '',          // 订单编号
                saleMan: ''           // 销售负责人
            },
            productList: [],         // 产品列表
            customerList: [],        // 分销商列表
            productOptions: [],      // 产品选项
            priceTerms: {
                totalOriginalPrice: 0,
                discountRate: 0,
                discountAmount: 0,
                totalPriceWithTax: 0,
                totalPriceWithoutTax: 0,
                grossMargin: 0
            },
            taxRate: 0.13,
        }
    },

    created() {
        this.getCustomerList();
        this.getProductList();
    },

    computed: {
        // 计算产品总价值
        totalProductValue() {
            return this.productList.reduce((sum, product) => {
                return sum + (product.salePrice * product.salesQuantity || 0)
            }, 0).toFixed(2)
        }
    },

    watch: {
        productList: {
            deep: true,
            handler() {
                this.calculatePrices()
            }
        },
        // 监听折扣率变化
        'priceTerms.discountRate': {
            handler() {
                this.calculatePrices()
            }
        }
    },

    methods: {
        // 查询全部分销商
        getCustomerList() {
            this.$axios.post('api/order-server/zf/queryAllByTrader')
                .then(response => {
                    if (response.data.code === 200) {
                        this.customerList = response.data.data
                    } else {
                        this.$message.error('获取分销商列表失败')
                    }
                })
        },

        // 查询全部产品
        getProductList() {
            this.$axios.post('api/order-server/zf/queryAllByProduct')
                .then(response => {
                    if (response.data.code === 200) {
                        this.productOptions = response.data.data
                    } else {
                        this.$message.error('获取产品列表失败')
                    }
                })
        },

        // 选择分销商后查询详细信息
        handleCustomerChange(distributorCode) {
            if (!distributorCode) return

            const formData = new FormData()
            formData.append('code', distributorCode)

            this.$axios.post('api/order-server/zf/queryByTraderCode', formData)
                .then(response => {
                    if (response.data.code === 200) {
                        const data = response.data.data
                        Object.assign(this.formData, {
                            distributorCode: data.distributorCode,
                            companyPhone: data.companyPhone,
                            companyContact: data.companyContact,
                            saleMan: data.saleMan,
                            validityEndDate: data.validityEndDate,
                            orderNo: data.orderNo
                        })
                    } else {
                        this.$message.error('获取分销商详情失败')
                    }
                })
                .catch(error => {
                    console.error('请求失败:', error)
                    this.$message.error('获取分销商详情失败')
                })
        },

        // 选择产品后查询详细信息
        handleProductChange(productId, index) {
            if (!productId) return

            const formData = new FormData()
            formData.append('id', productId)

            this.$axios.post('api/order-server/zf/queryByProductCode', formData)
                .then(response => {
                    if (response.data.code === 200) {
                        const data = response.data.data
                        this.$set(this.productList, index, {
                            id: data.id,
                            productName: data.productName,
                            productCode: data.productCode,
                            stockQuantity: data.stockQuantity,
                            salesQuantity: 0,
                            unit: data.unit,
                            salePrice: data.salePrice
                        })
                    } else {
                        this.$message.error('获取产品详情失败')
                    }
                })
                .catch(error => {
                    console.error('请求失败:', error)
                    this.$message.error('获取产品详情失败')
                })
        },

        // 添加产品行
        addProduct() {
            this.productList.push({
                id: '',
                productName: '',
                productCode: '',
                stockQuantity: 0,
                salesQuantity: 0,
                unit: '',
                salePrice: 0
            })
        },

        // 申请订单
        applyOrder() {
            // 首先验证必要数据
            if (!this.formData.distributorCode) {
                this.$message.error('请选择分销商')
                return
            }
            if (this.productList.length === 0) {
                this.$message.error('请至少添加一个产品')
                return
            }
            if (!this.formData.validityEndDate) {
                this.$message.error('请选择订单签订日期')
                return
            }

            // 构造请求数据
            const applyOrderDto = {
                // 分销商信息
                distributorCode: this.formData.distributorCode,
                companyPhone: this.formData.companyPhone,
                companyContact: this.formData.companyContact,
                // 订单信息
                validityEndDate: this.formData.validityEndDate,
                orderNo: this.formData.orderNo,
                saleMan: this.formData.saleMan,
                // 价格信息
                discountRate: this.priceTerms.discountRate,
                totalOriginalPrice: this.priceTerms.totalOriginalPrice,
                totalPriceWithTax: this.priceTerms.totalPriceWithTax,
                // 产品信息
                productList: this.productList.map(product => ({
                    productId: product.id,
                    productName: product.productName,
                    productCode: product.productCode,
                    salesQuantity: product.salesQuantity,
                    salePrice: product.salePrice,
                    unit: product.unit
                }))
            }

            // 发送请求
            this.$axios.post('api/order-server/zf/applyOrder', applyOrderDto)
                .then(response => {
                    if (response.data.code === 200) {
                        this.$message.success('订单申请成功')
                        // 成功后跳转到审批页面
                        this.$router.push('/order/orderApprove')
                    } else {
                        this.$message.error(response.data.message || '订单申请失败')
                    }
                })
                .catch(error => {
                    console.error('申请订单失败:', error)
                    this.$message.error('订单申请失败，请稍后重试')
                })
        },

        // 取消
        cancel() {
            this.$router.go(-1)
        },

        // 添加删除产品方法
        removeProduct(index) {
            this.$confirm('确认删除该产品?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.productList.splice(index, 1)
                this.$message.success('删除成功')
            }).catch(() => { })
        },

        // 计算所有价格
        calculatePrices() {
            // 总原价等于产品总价值
            this.priceTerms.totalOriginalPrice = this.totalProductValue

            // 计算优惠金额
            const originalPrice = parseFloat(this.priceTerms.totalOriginalPrice)
            const discountRate = parseFloat(this.priceTerms.discountRate)
            this.priceTerms.discountAmount = (originalPrice * discountRate / 100).toFixed(2)

            // 计算优惠后的金额
            const priceAfterDiscount = originalPrice - parseFloat(this.priceTerms.discountAmount)

            // 不含税金额就是优惠后的金额
            this.priceTerms.totalPriceWithoutTax = priceAfterDiscount.toFixed(2)

            // 含税金额 = 优惠后的金额 + 优惠后的金额 * 税率
            this.priceTerms.totalPriceWithTax = (priceAfterDiscount + (priceAfterDiscount * this.taxRate)).toFixed(2)

            // 计算毛利率 = (销售订单金额（含税）- 产品总价) / 销售订单金额（含税）* 100
            const profit = parseFloat(this.priceTerms.totalPriceWithTax) - originalPrice
            this.priceTerms.grossMargin = originalPrice ?
                (profit / this.priceTerms.totalPriceWithTax * 100).toFixed(2) : '0.00'
        },

        // 修改产品数量时重新计算
        handleQuantityChange() {
            this.calculatePrices()
        },

        // 修改页面切换处理方法
        handlePageChange(value) {
            if (value === 'orderApprove') {
                this.$router.push('/order/orderApprove')
            } else if (value === 'traderOrder') {
                this.$router.push('/order/traderOrder')
            }
        },
    }
}
</script>
<style scoped>
.trader-order {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 40px);
}

.section-card {
    margin-bottom: 20px;
    background: #fff;
    padding: 25px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.section-header i {
    font-size: 20px;
    margin-right: 8px;
    color: #409EFF;
}

.section-header span {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
}

.table-operations {
    margin-top: 20px;
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
}

.delete-btn {
    color: #F56C6C;
}

.delete-btn:hover {
    color: #f78989;
}

.form-actions {
    text-align: center;
    margin-top: 30px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 美化表格样式 */
.el-table {
    margin: 15px 0;
}

.el-table th {
    background-color: #f5f7fa !important;
    padding: 8px 0;
}

.el-table td {
    padding: 8px 0;
}

/* 美化按钮间距 */
.el-button+.el-button {
    margin-left: 12px;
}

/* 输入框统一样式 */
.el-input,
.el-select,
.el-date-picker {
    width: 100%;
}

/* 调整表格内部元素的样式 */
.el-table .el-select,
.el-table .el-input-number {
    width: 90%;
    margin: 0 auto;
}

/* 调整价格汇总的样式 */
.price-summary {
    margin-top: 20px;
    padding-top: 15px;
    text-align: right;
    font-size: 14px;
    color: #606266;
    font-weight: bold;
    border-top: 1px solid #EBEEF5;
}

/* 调整表格内按钮的样式 */
.el-table .el-button {
    padding: 5px 8px;
}

/* 确保表格内的输入框和选择器对齐 */
.el-table .el-input__inner,
.el-table .el-input-number__decrease,
.el-table .el-input-number__increase {
    height: 32px;
    line-height: 32px;
}

/* 调整表格列的对齐方式 */
.el-table .cell {
    padding: 0 10px;
}

/* 调整数字输入框的样式 */
.el-table .el-input-number {
    width: 150px;
    /* 增加输入框宽度 */
    margin: 0 auto;
}

/* 调整单位列的样式 */
.el-table .cell-unit {
    text-align: center;
    padding: 0 5px;
    /* 减少单位列的内边距 */
}

/* 确保数字输入框在单元格中居中 */
.el-table td.quantity-cell {
    text-align: center;
}

/* 修改页面切换下拉框样式 */
.page-switch {
    margin-bottom: 20px;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-switch .el-select {
    width: 200px;
}
</style>
